package com.jackrain.nea.web.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.core.schema.Column;
import com.jackrain.nea.core.schema.Table;
import com.jackrain.nea.core.schema.TableManager;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.service.AjaxUtils;
import com.jackrain.nea.service.ObjectSingle;
import com.jackrain.nea.util.Tools;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.PortletConfig.ObjectUIConfig;
import com.jackrain.nea.web.PortletConfig.PortletConfig;
import com.jackrain.nea.web.PortletConfig.PortletConfigManager;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.query.*;
import com.jackrain.nea.web.security.Directory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@Slf4j
@RestController
@Api(value = "TableQueryController", description = "单对象界面rest")
public class ObjectSingleController {

    @Autowired
    private ObjectSingle objuitl;
    
    @Autowired
    private PropertiesConf pconf;

    @ApiOperation(value="获取单对象按钮和关联明细表", notes="{\n" + "        \"tabinlinemode\": \"Y\",\n" + "        \"refcolid\": 1457,\n" + "        \"tableid\": 10101,\n" + "        \"tabrelation\": \"1:1\",\n" + "        \"tablename\": \"AD_TABLESQL\",\n" + "        \"tabledesc\": \"表SQL\"\n" + "      } 其中tabinlinemode 如果未N 则表示对应展示的明细表不可以编辑 refcolid 关联主表字段ID tablename 关联表表名 增加新参数ismaintable 默认为y 代表当前获取的表是主表，如果是明细传入n")
    @RequestMapping(path = "/p/cs/objectTab", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getObjectTab(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename, @RequestParam(value = "objid", required = true) Long objid,
                                    @RequestParam(value = "ismaintable", required = false,defaultValue = "y") String ismaintable) throws Exception {

        ValueHolder valueHolder = new ValueHolder();
        
        try {
            JSONObject data = new JSONObject();
            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
            
            QuerySession qsession = QueryUtils.createQuerySession(userWeb);
            
            objid=Tools.getLong(objid, -1);
            
            TableManager tm = qsession.getTableManager();
            
            Table table = tm.getTable(tablename);
            
            Boolean maintable=Tools.getBoolean(ismaintable,true);
            
            JSONObject cmd = objuitl.getCommandforTableId(table, userWeb.getPermission(table.getSecurityDirectory(tm)),maintable);

            JSONObject webact = objuitl.getWebActionforTableId(qsession, table);

            data.put("tabcmd", cmd);

            data.put("tabwebact", webact);
            
            if(maintable) {
                
                QueryUtils.checkObjDel(table, objid);

                JSONArray reftabs = objuitl.getReftables(qsession, table);
                
                data.put("reftabs", reftabs);

                Boolean objperm = false;

                if (objid > 0) {
                    objperm = userWeb.hasObjectPermission(table.getName(), objid, Directory.WRITE, qsession);
                }

                data.put("objperm", objperm);

            }
            //默认界面非只读模式
            data.put("objreadonly",false);

            if(cmd.getBoolean("actionSUBMIT")&&objid>0 ){
                
                int status=QueryEngine.getInstance().getSheetStatus(table.getRealTableName(),objid);
                
                if(status>1){
                    data.put("objreadonly",true);
                }

                data.put("status",status);
            }
            
            if(cmd.getBoolean("actionVOID")&&objid>0 ){
                
                Boolean isactive=Tools.getBoolean(QueryEngine.getInstance().getSheetVoid(table.getRealTableName(),objid),true);
                
                if(!isactive){
                    data.put("objreadonly",true);
                }

                data.put("isactive",isactive);
                
            }
           
            
         
            valueHolder.put("code", 0);
            valueHolder.put("data", data);

            return valueHolder.toJSONObject();

        } catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("msg", e.getMessage());
            return valueHolder.toJSONObject();
        }


    }


    @ApiOperation(value="获取主表字段", notes="objid如果不为空则返回对应数据保存的值如果-1或查询不到则默认值")
    @RequestMapping(path = "/p/cs/getObject", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getObject(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename,@RequestParam(value = "objid", required = false)  Long objid) throws Exception {

        ValueHolder valueHolder = new ValueHolder();

        try {
            JSONObject data = new JSONObject();

            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");

            QuerySession qsession = QueryUtils.createQuerySession(userWeb);

            TableManager tm = qsession.getTableManager();

            Table table = tm.getTable(tablename);

            objid=Tools.getLong(objid, -1);
            
            JSONArray columns=new JSONArray();

            if(objid<0) {
                columns = objuitl.getColumnbyHr(qsession, table, new int[]{0, 1, 2}, objid, -1);
            }else{
                columns = objuitl.getColumnbyHr(qsession, table, new int[]{2, 3}, objid, -1);
            }
                
            

            ObjectUIConfig objConfig=(ObjectUIConfig)PortletConfigManager.getInstance().getPortletConfig(table.getUIConfigId(), PortletConfig.TYPE_OBJECT_UI);

            data.put("objviewcol",objConfig.getColsPerRow());
            
            data.put("addcolums", columns);

            valueHolder.put("code", 0);

            valueHolder.put("data", data);

            return valueHolder.toJSONObject();

        }catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("msg", e.getMessage());
            return valueHolder.toJSONObject();
        }


    }


    @ApiOperation(value="获取对应明细表内容", notes="" +
            "POST /p/cs/objectTab 接口返回 对应所属的关联表有几个 对应的关联字段是什么 tablename，refcolid 作为本次请求的关键参数。objid是当前主表的记录searchdata 是为了配合明细查询的功能 下拉几行 当前第几页" +
            "参数参考 table=AD_REFBYTABLE&objid=10010&refcolid=88&searchdata={\"column_include_uicontroller\":true,\"range\":10,\"startindex\":0}")
    @RequestMapping(path = "/p/cs/objectTableItem", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getObjectTableItem(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename, @RequestParam(value = "objid", required = true) Long objid,@RequestParam(value = "refcolid", required = true) int refcolid,@RequestParam(value = "searchdata", required = true) String obj) throws Exception {

        ValueHolder valueHolder = new ValueHolder();
        log.debug("query data ->("+ obj+")");
        try {

            JSONObject jo=JSON.parseObject(obj);
            
            JSONObject data = new JSONObject();

            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");

            QuerySession qsession = QueryUtils.createQuerySession(userWeb);

            TableManager tm = qsession.getTableManager();

            Table table = tm.getTable(tablename);

            objid = Tools.getLong(objid, -1);
            
            jo.put("objectIds", refcolid + "=" + objid);
            
            QueryRequest query= AjaxUtils.parseQuery(jo, qsession, userWeb.getId(), userWeb.getLocale(),table);
            log.debug("query sql->"+query.toSQL());

            log.debug("query FullRange sql->"+query.toFullRangeSubTotalSQL());
            log.debug("query Range sql->"+query.toSQLWithRange());

            QueryResult qr= QueryEngine.getInstance().doQuery( query);
            
            JSONObject result=qr.getColumnDataObj(true);
            
            result.put("tabth",query.SelectbyDisObj(true,userWeb.getLocale()));
         
            
            result.put("tabname",table.getName());

            String rangeconf=pconf.getProperty("query.select.range","10,20,50,100");

            JSONArray selectrange= (JSONArray) JSON.toJSON(Tools.parseIntArray(rangeconf,","));
            
            result.put("selectrange",selectrange);
            
            result.put("defaultrange",query.getRange());
            
            valueHolder.put("code", 0);
            valueHolder.put("datas", result);
            
            return valueHolder.toJSONObject();

        } catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("msg", e.getMessage());
            return valueHolder.toJSONObject();
        }


    }



    @ApiOperation(value="获取明细表输入字段", notes="商品数量模式、标准模式、新增模式")
    @RequestMapping(path = "/p/cs/inputForitem", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getInputForitem(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename,@RequestParam(value = "inlinemode", required = true)  String inlinemode) throws Exception {

        ValueHolder valueHolder = new ValueHolder();

        try {
            JSONObject data = new JSONObject();

            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");

            QuerySession qsession = QueryUtils.createQuerySession(userWeb);

            TableManager tm = qsession.getTableManager();

            Table table = tm.getTable(tablename);

            JSONArray  jhrs= new JSONArray();
            
            if("B".equalsIgnoreCase(inlinemode)){
                
                if (table.getJSONProps() != null) {
                    JSONObject jor= table.getJSONProps();
                    //{"pdtcol":"","qtycol":""}
                    if(jor.containsKey("pdtcol")&&jor.containsKey("qtycol")){
                        JSONObject inpubobj= new JSONObject();
                        inpubobj.put("colname",jor.getString("pdtcol"));
                        inpubobj.put("desc", Resources.getMessage("款号",qsession.getLocale()));
                        inpubobj.put("display", "text");
                        inpubobj.put("type", "STRING");

                        jhrs.add(inpubobj);

                        inpubobj= new JSONObject();
                        inpubobj.put("colname",jor.getString("qtycol"));
                        inpubobj.put("desc", Resources.getMessage("数量",qsession.getLocale()));
                        inpubobj.put("display", "text");
                        inpubobj.put("type", "NUMBER");
                        
                        jhrs.add(inpubobj);
                    } else{
                        throw new NDSException(Resources.getMessage(table+"未设置指定商品数量扩展参数{\"pdtcol\":\"\",\"qtycol\":\"\"}",qsession.getLocale()));
                    }
                } 
                   
                
            }


            if("Y".equalsIgnoreCase(inlinemode)){

               ArrayList columns=table.getColumns(new int[]{1,3},false,userWeb.getSecurityGrade());
                
                for (int i = 0; i < columns.size(); i++) {
                    Column col= (Column) columns.get(i);

                    JSONObject inpubobj=objuitl.getColumnObject(col,qsession,true,null);
                    jhrs.add(inpubobj);

                }

            }

            if(jhrs.size()>0) {
                data.put("inpubobj",jhrs);
            }
            valueHolder.put("code", 0);
            valueHolder.put("data", data);

            return valueHolder.toJSONObject();
        } catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("msg", e.getMessage());
            return valueHolder.toJSONObject();
        }


    }
    
    @ApiOperation(value="获取明细表单对象字段", notes="objid如果不为空则返回对应数据保存的值如果-1或查询不到则默认值")
    @RequestMapping(path = "/p/cs/itemObj", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getItemObj(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename,@RequestParam(value = "objid", required = true)  Long objid,@RequestParam(value = "refcolid", required = true)  int refcolid) throws Exception {

        ValueHolder valueHolder = new ValueHolder();

        try {
            JSONObject data = new JSONObject();

            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");

            QuerySession qsession = QueryUtils.createQuerySession(userWeb);

            TableManager tm = qsession.getTableManager();

            Table table = tm.getTable(tablename);

            objid=Tools.getLong(objid, -1);
            
            refcolid=Tools.getInt(refcolid, -1);
            
            JSONArray columns = objuitl.getColumnbyHr(qsession, table,new int[]{0,1,2,3},objid,refcolid);
            
            ObjectUIConfig objConfig=(ObjectUIConfig)PortletConfigManager.getInstance().getPortletConfig(table.getUIConfigId(), PortletConfig.TYPE_OBJECT_UI);

            data.put("objviewcol",objConfig.getColsPerRow());

            data.put("addcolums", columns);

            valueHolder.put("code", 0);

            valueHolder.put("data", data);
            
            valueHolder.put("itemid", com.jackrain.nea.core.db.Tools.getIdbyObjectId(table,qsession,refcolid,objid));

            return valueHolder.toJSONObject();

        }catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("msg", e.getMessage());
            return valueHolder.toJSONObject();
        }


    }


    }
